-- ------------------------------------------------------------------------
-- > lumAutobot (Kreoss @ Quel'Thalas EU) <
-- ------------------------------------------------------------------------
-- Credits: Tekkub, evl, grennon, turkoid, mikma, Blooblahguy and zork.
-- ------------------------------------------------------------------------

	local ab = CreateFrame("Frame", "lumAutobotFrame")
	
-- ------------------------------------------------------------------------
-- > 0. Configuration and Media
-- ------------------------------------------------------------------------

	local use_auto_sell = true -- Use Auto sell module
	local use_auto_invite = true -- Use Auto accept friends invites module
	local use_auto_release = true -- Use Auto release in pvp module
	local use_auto_rez = true -- Use Auto ressurect out of combat module
	
-- ------------------------------------------------------------------------
-- > 1. Constants and Variables
-- ------------------------------------------------------------------------
	
	lumAutobotDB = {} -- Item List to Auto-Sell
	
	local DupPot = nil	-- Check for Repeated Sell Prints
	local DupRep = nil	-- Check for Repeated Repairs Prints
	local SellTime = nil	-- Current Time for the Grey Sells
	local RepairTime = nil	-- Current Time for the Repairs

-- ------------------------------------------------------------------------
-- > 2. Functions
-- ------------------------------------------------------------------------

	-- Sells Bag Items
	function SellItems()
	
		if(SellTime == nil) then SellTime = GetTime() end

		local Pot = 0
		for bag = 0,4 do
			if GetContainerNumSlots(bag) > 0 then
				for slot=1, GetContainerNumSlots(bag) do
					local Item = GetContainerItemLink(bag, slot)
					if(Item) then
						ItemQuality = select(3, GetItemInfo(Item))
						ItemPrice = select(11, GetItemInfo(Item))
						ItemCount = select(2, GetContainerItemInfo(bag, slot))					
						-- Saved List Items
						Pot = Pot + SellListItem(Item, bag, slot, ItemQuality, ItemPrice, ItemCount)				
						-- Grey Items
						Pot = Pot + SellGreyItem(Item, bag, slot, ItemQuality, ItemPrice, ItemCount)
					end
				end
			end
		end
		
		local SellTimeAgo = GetTime() - SellTime
		
		if(Pot ~= 0 and ( (Pot ~= DupPot) or (Pot == DupPot and SellTimeAgo > 2) )) then
			print("|cff267dffAuto Sell:|cffffffff  " .. GetCoinTextureString(Pot,13))
			DupPot = Pot
			if(SellTimeAgo > 2) then SellTime = nil DupPot = nil end
		end	
	end
	
	-- Sell a bag Item if it's in the DB List
	function SellListItem(Item, bag, slot, ItemQuality, ItemPrice, ItemCount)

		local Sum = 0
		ItemName = select(1, GetItemInfo(Item))
		i = ListItemExists(ItemName)
		if (i) then
			if(ItemQuality <= 1 and ItemPrice ~= 0) then
				UseContainerItem(bag, slot)
				Sum = (ItemPrice * ItemCount)
				return Sum
			else
				Sum = 0
			end
		else
			Sum = 0
		end
		return Sum
	end
	
	-- Checks if an Item exists in the DB List and returns its Index
	function ListItemExists(ItemName)

		local index	
		for i=1, #lumAutobotDB do
			if (ItemName == select(1, GetItemInfo(lumAutobotDB[i]))) then
				index = i
				return index
			else
				index = nil
			end
		end
		return index
	end
	
	-- Lists the Current Items in the DB in the Chatframe
	function ListTable()
	
		print("|cff267dffItems to Sell:|r")
		if(#lumAutobotDB ~= 0) then
			for i=1, #lumAutobotDB do
				print("|cff26d9ff"..i..".|r " .. lumAutobotDB[i])
			end
		else
			print("|cff26d9ff- empty -|r ")
		end
	end
	
	-- Sell a bag Item if it's Grey
	function SellGreyItem(Item, bag, slot, ItemQuality, ItemPrice, ItemCount)
	
		if (ItemQuality == 0 and ItemPrice ~= 0) then
			UseContainerItem(bag, slot)
			return (ItemPrice * ItemCount)
		else
			return 0
		end
	end
	
	-- Auto Repair
	function AutoRepair()
	
		if(RepairTime == nil) then RepairTime = GetTime() end

		local RepairCost = GetRepairAllCost()
		local MyMoney = GetMoney()
		if (CanMerchantRepair() and RepairCost > 0) then
			local MyGuildMoney = GetGuildBankWithdrawMoney()
			local RepairTimeAgo = GetTime() - RepairTime
			
			if(UseGuildFunds and IsInGuild() and (MyGuildMoney == -1 or MyGuildMoney > 0)) then
				local TotalGuildMoney = GetGuildBankMoney()
					if(MyGuildMoney > TotalGuildMoney or MyGuildMoney == -1) then
						MyGuildMoney = TotalGuildMoney
					end
				if(MyGuildMoney >= RepairCost and ( (RepairCost ~= DupRep) or (RepairCost == DupRep and RepairTimeAgo > 2) )) then
					RepairAllItems(1)
					print("|cffe4ff00Repair-Cost from Guild Funds:|cffffffff  " .. GetCoinTextureString(RepairCost,13))
					DupRep = RepairCost
					if(RepairTimeAgo > 2) then RepairTime = nil DupRep = nil end
				else
					print("|cfff10b62Insufficient Guild Funds to Repair|r")
				end
			else
				if(MyMoney >= RepairCost and ( (RepairCost ~= DupRep) or (RepairCost == DupRep and RepairTimeAgo > 2) )) then
					RepairAllItems()
					print("|cffe4ff00Repair-Cost:|cffffffff  " .. GetCoinTextureString(RepairCost,13))
					DupRep = RepairCost
					if(RepairTimeAgo > 2) then RepairTime = nil DupRep = nil end
				elseif (MyMoney < RepairCost) then
					print("|cfff10b62Insufficient Funds to Repair|r")
				end
			end
		end
	end
		
	-- Auto Release
	function AutoRelease()
	
		local Zone = GetRealZoneText()
		if (MiniMapBattlefieldFrame.status == "active" or Zone == "Wintergrasp") then RepopMe() end
	end
	
	-- Auto Accept Ressurrect
	function AutoRessurrect(self,event,...)
	
		local rezzer = ...
		
		if (UnitAffectingCombat(rezzer) == nil and GetCorpseRecoveryDelay() == 0) then -- Excludes Rebirth
			AcceptResurrect()
			DoEmote("thank", rezzer)
		else
			local s = "Thanks for the Rez! I still have a "..GetCorpseRecoveryDelay().." seconds delay till I can accept it."
			SendChatMessage(s, "WHISPER", nil, rezzer);
			return
		end	
	end
	
	-- Auto Accept Party/Raid Invite from Friends
	function IsRealmFriend(self,event,...)
	
		local char = ...
		
		ShowFriends() -- Update Friends List
		for k = 1, GetNumFriends() do
			myFriend = select(1, GetFriendInfo(k))
			if(char == myFriend) then
				return true
			end
		end
	end
	
	-- Auto Accept Party/Raid Invite from RealID Friends
	function IsRealIDFriend(self,event,...)
	
		local char = ...
		
		if BNFeaturesEnabledAndConnected() then
			ShowFriends() -- Update Friends List
			for k = 1, BNGetNumFriends() do
				presenceID,_,_,_,_,client,isOnline = BNGetFriendInfo(k)
				if (client == "WoW" and isOnline) then
					if(char == select(2, BNGetToonInfo(presenceID)) and GetRealmName() == select(4, BNGetToonInfo(presenceID))) then
						return true
					end
				end
			end
		end
	end
		
	-- Hide Party Invite Popup
	function HidePartyInvitePopup()
	
		StaticPopup_Hide("PARTY_INVITE")
	end
		
	--------------------
	-- Event Functions
	--------------------
		
	function ab:MERCHANT_SHOW(self,event)

		SellItems()		
		AutoRepair()
	end
	
	function ab:PARTY_INVITE_REQUEST(self,event,...)

		if(IsRealmFriend(self,event,...) or IsRealIDFriend(self,event,...)) then AcceptGroup(self,event,...) end
	end
	
	function ab:PARTY_MEMBERS_CHANGED(self,event)
	
		HidePartyInvitePopup() 
	end
	
	function ab:PLAYER_DEAD(self,event)
	
		AutoRelease()
	end
				
	function ab:RESURRECT_REQUEST(self,event,...)

		AutoRessurrect(self,event,...)
	end
	
	function ab:ADDON_LOADED(self,event,...)

		local addon_name = ...
		
		if addon_name == "lumAutobot" then	
			-- Events
			ab:RegisterEvent("MERCHANT_SHOW")
			ab:RegisterEvent("PARTY_INVITE_REQUEST")
			ab:RegisterEvent("PARTY_MEMBERS_CHANGED")
			ab:RegisterEvent("PLAYER_DEAD")
			ab:RegisterEvent("RESURRECT_REQUEST")
		end
	end
	
	function ab:OnEvent(self,event,...)
	
		local addon_name = ...
		
		if ((event == "ADDON_LOADED") and (addon_name == "lumAutobot")) then self:ADDON_LOADED(self,event,...)
		elseif (event == "MERCHANT_SHOW" and use_auto_sell) then self:MERCHANT_SHOW(self,event,...)
		elseif (event == "PARTY_INVITE_REQUEST" and use_auto_invite) then self:PARTY_INVITE_REQUEST(self,event,...)
		elseif (event == "PARTY_MEMBERS_CHANGED" and use_auto_invite) then self:PARTY_MEMBERS_CHANGED(self,event,...)
		elseif (event == "PLAYER_DEAD" and use_auto_release) then self:PLAYER_DEAD(self,event,...)
		elseif (event == "RESURRECT_REQUEST" and use_auto_rez) then self:RESURRECT_REQUEST(self,event,...)
		end	
	end
	
	---------
	-- Main
	---------
		
	SLASH_AUTOBOT1 = "/autobot"
	
	local cmdHandler = function(msg)
		
		local cmd, item = msg:match("^(%S*)%s*(.-)$")
		if ( cmd == "add" and (item ~= "" and tonumber(select(11, GetItemInfo(item)))>0 and select(3, GetItemInfo(item)) == 1) ) then -- Common Quality Only and Can be sold
			if(not ListItemExists(select(1, GetItemInfo(item)))) then -- Not Duplicated
				table.insert(lumAutobotDB, item)
				print("|cffade516Inserted: |r" .. item)
			end
		elseif ( cmd == "del" ) then
			if(select(11, GetItemInfo(item))) then -- if is ItemLink
				local i = ListItemExists(select(1, GetItemInfo(item)))
				if(i) then table.remove(lumAutobotDB, i) print("|cffe51616Removed: |r" .. item) end
			elseif(type(tonumber(item)) == "number" and tonumber(item) <= #lumAutobotDB) then -- if is number
				print("|cffe51616Removed: |r" .. lumAutobotDB[tonumber(item)])
				table.remove(lumAutobotDB, item)
			end
		elseif ( cmd == "list" ) then
			ListTable() -- List the Items in the DB vector
		elseif ( cmd == "wipe" ) then
			wipe(lumAutobotDB)
			print("|cffe51616Database Erased!|r")
		else
			print("|cffe4ff00Syntax:|r")
			print("|cfff1ff7c/autobot [add] Item|r")
			print("|cfff1ff7c/autobot [del] Item or ItemIndex|r")
			print("|cfff1ff7c/autobot [list]|r")
			print("|cfff1ff7c/autobot [wipe]|r")
		end
	end
	
	SlashCmdList["AUTOBOT"] = cmdHandler


-- ------------------------------------------------------------------------
-- > 3. Events
-- ------------------------------------------------------------------------

	ab:SetScript("OnEvent", function(self,event,...) self:OnEvent(self,event,...) end)
	ab:RegisterEvent("ADDON_LOADED")